package com.joysuccess.minaserver.minaserver;

import com.joysuccess.minaserver.minaserver.raw.DecoderResultType;
import com.joysuccess.minaserver.minaserver.raw.SocketMesaageManager;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.springframework.stereotype.Component;

/**
 * 字节数组解码器
 *
 * @author shenchao
 */
@Component
public class ByteArrayDecoder extends CumulativeProtocolDecoder {

    @Override
    public boolean doDecode(IoSession session, IoBuffer in,
                            ProtocolDecoderOutput out) throws Exception {
        //前16字节是包头
        if (in.remaining() > 16) {
            // 标记当前position的快照标记mark，以便后继的reset操作能恢复position位置
            in.mark();
            //包头
            byte[] head = new byte[16];
            in.get(head);
            byte[] command = SocketMesaageManager.getCommand(head);
            String insStr = SocketMesaageManager.getIns(command);
            String insType = SocketMesaageManager.getInsType(command);
            int bodyLen = SocketMesaageManager.getBodyLen(head);
            int mLen = in.remaining();
            if (mLen < bodyLen) {
                // 如果消息内容不够，则重置恢复position位置到操作前,进入下一轮, 接收新数据，以拼凑成完整数据
                in.reset();
                return false;
            } else {
                byte[] body = new byte[bodyLen];
                in.get(body);
                String bodyStr = SocketMesaageManager.getBodyStr(body);
                DecoderResultType drt = new DecoderResultType();
                drt.setIns(insStr);
                drt.setInsType(insType);
                drt.setBody(bodyStr);
                out.write(drt);
                if (in.remaining() > 0) {
                    // 如果读取一个完整包内容后还粘了包，就让父类再调用一次，进行下一次解析
                    return true;
                }
            }
        }
        // 处理成功，让父类进行接收下个包
        return false;
    }
}